<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class write_article_views extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'write_article_views';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '把文章阅读数量从redis写入mysql';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $all = Redis::hgetall('global_views');
        $now  =time();
        $rs = [];
        foreach($all as $key=>$time){
            $key = explode('-', $key);
            $ip = $key[0];
            $id = $key[1];
            if( $now-$time>3600 ){
                $rs[$id][] = $ip;
                Redis::hdel('global_views',$key);
            }
        }
        foreach($rs as $id=>$ips){
            $count = count($rs[$id]);
            DB::table('theme')->where('id',$id)->increment('views',$count);
        }
    }
}
